package com.enjoyor.health.HGPT.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.enjoyor.health.HGPT.core.config.WxAppConfig;
import com.enjoyor.health.HGPT.core.dto.FullUserInfoAppDto;
import com.enjoyor.health.HGPT.core.dto.UserInfoAppDto;
import com.enjoyor.health.HGPT.core.dto.UserWatchConfigDto;
import com.enjoyor.health.HGPT.core.entity.*;
import com.enjoyor.health.HGPT.core.service.IUserInfoAppService;
import com.enjoyor.health.HGPT.core.service.IUserInfoMiniappService;
import com.enjoyor.health.HGPT.core.service.IUserInfoMiniappSessionService;
import com.enjoyor.health.HGPT.core.service.IUserInfoService;
import com.enjoyor.health.HGPT.util.EncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Zhu Min
 * @date 2023/10/18 13:33
 */
@Slf4j
@Service
public class BizUserService {

    @Autowired
    private IUserInfoService userInfoService;
    @Autowired
    private IUserInfoMiniappService userInfoMiniappService;
    @Autowired
    private IUserInfoMiniappSessionService userInfoMiniappSessionService;
    @Autowired
    private IUserInfoAppService userInfoAppService;
    @Autowired
    private WxAppConfig wxAppConfig;
    /**
     * 登陆更新token信息
     */
    public void getOpenIdSession(String openId, String seeionKey, String token){
        String uuidStr = IdUtil.simpleUUID();
        LocalDateTime now = LocalDateTime.now();

        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        if (userInfoMiniapp != null){
            UserInfoMiniapp userInfoMiniappNew = new UserInfoMiniapp();
            userInfoMiniapp.setOpenId(openId);
            userInfoMiniapp.setRegisterTime(now);
            userInfoMiniapp.setStorageTime(now);
            userInfoMiniapp.setUpdateTime(now);
            userInfoMiniappService.save(userInfoMiniappNew);
            log.info("user_info_miniapp插入成功：'{}", openId);
        }else {
            log.info("user_info_miniapp插入停止，open_id已存在: '{}", openId);
        }

        UserInfoMiniappSession userInfoMiniappSession = new UserInfoMiniappSession();
        userInfoMiniappSession.setId(uuidStr);
        userInfoMiniappSession.setOpenId(openId);
        userInfoMiniappSession.setSessionKey(seeionKey);
        userInfoMiniappSession.setToken(token);
        userInfoMiniappSession.setEffectiveTime(now);
        userInfoMiniappSession.setStorageTime(now);
        userInfoMiniappSession.setUpdateTime(now);
        userInfoMiniappSessionService.save(userInfoMiniappSession);
        log.info("user_info_miniapp_session插入成功");
    }

    /**
     * 根据登录OPEN_ID获取保存的手机号
     * @return 手机号码
     */
    public String getOpenIdPhone(String openId){
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        if (userInfoMiniapp == null){
            log.info("open_id-'{}'-user_info_miniapp表不存在open_id", openId);
            return null;
        }else {
            String phone = userInfoMiniapp.getPhone();
            if (StringUtils.isNotBlank(phone)){
                log.info("open_id-'{}'-有手机号{}", openId, phone);
            }else {
                log.info("open_id-'{}'-无手机号", openId);
            }
            return phone;
        }
    }

    /**
     * 用户注册，插入数据
     */
    public void regUser(UserInfo userInfo, UserInfoMiniapp userInfoMiniapp){
        userInfoService.insertOrUpdateUserInfo(userInfo);
        userInfoMiniappService.insertOrUpdateUserInfoMiniapp(userInfoMiniapp);
    }

    public UserInfoMiniappSession getDbToken(String openId){
        return userInfoMiniappSessionService.getByOpenId(openId);
    }

    public void updateUserInfo(String openId, String name, String height, String weight){
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userInfoMiniapp.getUserId());
        userInfo.setName(name);
        userInfo.setHeight(height);
        userInfo.setWeight(weight);
        userInfo.setUpdateTime(LocalDateTime.now());
        userInfoService.updateUserInfo(userInfo);
    }

    public int captcha(String captcha, String userId, String openId){
        String phone = captcha;
        List<UserInfo> userInfoList = userInfoService.getUserInfoByPhone(phone);
        UserInfo userInfo = userInfoList == null? null : userInfoList.get(0);
        UserInfoMiniapp userInfoMiniapp = userInfoMiniappService.getUserInfoMiniappByOpenId(openId);
        if (userInfo == null && StringUtils.isNotBlank(phone)){
            if (userInfoMiniapp != null){
                String p =  userInfoMiniapp.getPhone();
                if (p.length() == 6){
                    //
                    userInfoMiniappService.updatePhoneAndUserId(phone, userId, openId);
                    return 1;
                }else if (p.length() ==1){
                    if (phone.equals(p)){
                        return 1;
                    }else {
                        log.info("邀请码与用户的11位邀请码不相等");
                        return 0;
                    }
                }else {
                    log.info("邀请码长度不对");
                    return 0;
                }
            }else {
                //sql_update_user_info_miniapp
                userInfoMiniappService.updatePhoneAndUserId(phone, userId, openId);
                return 1;
            }
        }else {
            return 0;
        }
    }

    public UserInfo getByUserId(String userId){
        return userInfoService.getById(userId);
    }

    public UserInfo getByPhone(String phone){
        List<UserInfo> userInfoList = userInfoService.getUserInfoByPhone(phone);
        if (userInfoList!= null && userInfoList.size() >0){
            return userInfoList.get(0);
        }else {
            return null;
        }
    }

    public UserInfoApp getUserInfoAppByPhone(String phone){
        return userInfoAppService.getByPhone(phone);
    }

    public UserInfoApp getUserInfoAppByUserId(String userId){
        return userInfoAppService.getByUserId(userId);
    }

    public FullUserInfoAppDto regAppNewUser(String phone){
        LocalDateTime currentTime = LocalDateTime.now();
        String userId = new String(EncryptUtil.encrypt(phone.getBytes(), wxAppConfig.getUserIdKey().getBytes()));
        UserInfoApp userInfoApp = new UserInfoApp();
        userInfoApp.setUserId(IdUtil.simpleUUID());
        userInfoApp.setRegisterTime(currentTime);
        userInfoApp.setPhone(phone);
        userInfoApp.setUserId(userId);
        userInfoApp.setStorageTime(currentTime);
        userInfoApp.setUpdateTime(currentTime);
        userInfoAppService.save(userInfoApp);
        UserInfo userInfo = getByPhone(phone);
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setName(phone);
            userInfo.setPhone(phone);
            userInfo.setRegTime(currentTime);
            userInfo.setStorageTime(currentTime);
            userInfo.setUpdateTime(currentTime);
            userInfoService.save(userInfo);
        }
        FullUserInfoAppDto dto = new FullUserInfoAppDto();
        dto.setUserInfo(userInfo);
        dto.setUserInfoApp(userInfoApp);
        return dto;
    }

    public UserInfoAppDto updateAppUserInfo(UserInfoAppDto dto){
        UserInfo userInfo = getByUserId(dto.getId());
        userInfo.setName(dto.getName());
        userInfo.setIdNumber(dto.getIdNumber());
        userInfo.setGender(dto.getGender());
        userInfo.setHeight(dto.getHeight());
        userInfo.setWeight(dto.getWeight());
        userInfo.setAge(dto.getAge());
        userInfo.setUpdateTime(LocalDateTime.now());
        userInfoService.updateUserInfo(userInfo);
        BeanUtil.copyProperties(userInfo, dto);
        return dto;
    }

    public int updateAppWatchConfig(UserWatchConfigDto dto){
        return userInfoAppService.updateConfig(dto);
    }


    public boolean deleteAccount(String userId){
        List<UserInfoMiniapp> userInfoMiniAppList = userInfoMiniappService.getByUserId(userId);
        UserInfoApp userInfoApp = userInfoAppService.getByUserId(userId);
        UserInfo userInfo = userInfoService.getById(userId);
        List<UserInfoMiniappSession> userInfoMiniappSessionList = new ArrayList<>();
        if (userInfoMiniAppList != null){
            for (UserInfoMiniapp userInfoMiniapp : userInfoMiniAppList) {
                UserInfoMiniappSession userInfoMiniappSession = userInfoMiniappSessionService.getByOpenId(userInfoMiniapp.getOpenId());
                if (userInfoMiniappSession != null){
                    userInfoMiniappSessionList.add(userInfoMiniappSession);
                }
            }
        }
        //开始删除
        for (UserInfoMiniappSession userInfoMiniappSession : userInfoMiniappSessionList) {
            userInfoMiniappSessionService.removeById(userInfoMiniappSession.getId());
        }
        if (userInfoApp != null){
            userInfoAppService.removeById(userInfoApp.getId());
        }
        if (userInfoMiniAppList != null){
            for (UserInfoMiniapp userInfoMiniapp : userInfoMiniAppList) {
                userInfoMiniappService.removeById(userInfoMiniapp.getOpenId());
            }
        }
        if (userInfo != null){
            userInfoService.removeById(userInfo.getId());
        }
        return true;
    }

}
